import React, { Component } from 'react';
import { CategoryGet, ProductAdd ,ProductUpdate} from "../../../api/index"
import PicturesWall from "./PicturesWall"
import { Card, Input, Button, Icon, Form, Cascader, message } from "antd"
import RichTextEditor from "./RichTextEditor"


const { TextArea } = Input;


class AddProduct extends Component {

    constructor(props) {
        super();
        this.img = React.createRef();  //生成图片上传组件的标识
        this.des = React.createRef();  //生成富文本组件的标识
        this.modify = false;  //判断是添加商品页面还是商品修改页面的标识
    }

    state = {
        options: [],
        child: []
    }

    UNSAFE_componentWillMount() {

        if (this.props.location.product) {
            this.modify = true;
            this.product = this.props.location.product || {}
        } else {
            this.modify = false;
            this.product = {}
        }

    }


    componentDidMount() {
        this.getcategory();
    }

    // 返回商品管理页面
    back = () => {
        this.props.history.push("/admin/product/")
    }

    //级联选择器点击时触发的事件 
    onChange = (value, selectedOptions) => {
        // console.log(value, selectedOptions);
    };
    //级联选择器点击时触发的事件 
    loadData = async selectedOptions => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        const list = await CategoryGet({ "categoryGrade": targetOption.value })

        targetOption.loading = false;
        if (list.length) {
            targetOption.children = list.map(item => {
                return {
                    value: item._id,
                    label: item.categoryName,
                    isLeaf: true
                }
            })
        } else {
            targetOption.isLeaf = true;
        }
        this.setState({
            options: [...this.state.options],
        });
    };

    // 提交按钮
    submit = () => {
        this.props.form.validateFields(async (err, values) => {
            //通过标识获取到上传图片组件，并执行该子组件中的getImg方法，获取到对应的图片数组
            const proPictures = this.img.current.getImg()
            const proDes = this.des.current.getDes();
            values.proPictures = proPictures;
            values.proDes = proDes;

            const { _id } = this.product;
            if (_id) {
                values._id = _id;
                console.log(values);
                const result = await ProductUpdate(values)
                const { status, msg } = result;
                if (status) {
                    message.success(msg)
                    this.props.history.push("/admin/product/")
                } else {
                    message.error(msg)
                }
            } else {
                const result = await ProductAdd(values)
                const { status, msg } = result;
                if (status) {
                    message.success(msg)
                    this.props.history.push("/admin/product/")
                } else {
                    message.error(msg)
                }
            }


        });
    }

    // 获取分类
    getcategory = async (args) => {
        const grade = args ? args : "0"
        const list = await CategoryGet({ "categoryGrade": grade });
        let options;
        if (grade === "0") {
            options = list.map(item => {
                return {
                    value: item._id,
                    label: item.categoryName,
                    isLeaf: false
                }
            })
            this.setState({
                options
            })
        }
        const { proCategory } = this.product;
        if (proCategory && proCategory.length === 2) {
            const child = await CategoryGet({ "categoryGrade": proCategory[0] });
            const option = this.state.options.find((item) => item.value === proCategory[0])
            option.children = child.map(item => {
                return {
                    value: item._id,
                    label: item.categoryName,
                    isLeaf: true
                }
            })
            const options = this.state.options;
            this.setState({
                options
            }, function () {
                console.log(this.state.options)
            })
        }
    }


    render() {
        const { getFieldDecorator } = this.props.form;

        // proPictures: (2)["http://localhost:5000/uploads/1581664118812.jpg", "http://localhost:5000/uploads/1581664123711.jpg"]
        // proCategory: ["5e401ce13353ac3d7c8ccb7e"]
        // _id: "5e4647822fc1833b1023f63e"
        // proName: "刘佩"
        // proIntro: "好看"
        // proPrice: "123123"
        // proDes: "<p>好看呐</p>↵"
        const { proPictures, proCategory, proName, proIntro, proPrice, proDes } = this.product;

        // 栅格
        const formItemLayout = {
            labelCol: {
                sm: { span: 6 },

            },
            wrapperCol: {
                sm: { span: 12 },

            },
        };

        const title = (
            <span>
                <Button type="primary" onClick={this.back}>
                    <Icon type="left"></Icon>
                    返回
                </Button>
                <span style={{ marginLeft: 20 }}>
                    当前页面：<span style={{ color: "#3D628D", fontSize: 20 }}>{this.modify ? "修改商品信息" : "添加商品"}</span>
                </span>
            </span>
        )

        return (
            <div>
                <Card title={title} style={{ borderBottom: "none" }}>
                    <Form {...formItemLayout}>
                        <Form.Item label="商品名称">
                            {getFieldDecorator('proName', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入商品名称！',
                                    },
                                ],
                                initialValue: this.modify ? proName : "",
                            })(<Input/>)}
                        </Form.Item>
                        <Form.Item label="商品简介">
                            {getFieldDecorator('proIntro', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入商品描述！',
                                    },
                                ],
                                initialValue: this.modify ? proIntro : "",
                            })(<TextArea />)}
                        </Form.Item>
                        <Form.Item label="商品价格">
                            {getFieldDecorator('proPrice', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入商品价格！',
                                    },
                                ],
                                initialValue: this.modify ? proPrice : "",
                            })(<Input type={"number"} min={0} addonAfter="元" />)}
                        </Form.Item>
                        <Form.Item label="商品分类">
                            {getFieldDecorator('proCategory', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择分类！',
                                    },
                                ],
                                initialValue: this.modify ? proCategory : "",
                            })(<Cascader
                                options={this.state.options}
                                loadData={this.loadData}
                                onChange={this.onChange}
                                changeOnSelect
                                placeholder="请选择分类"
                            />)}
                        </Form.Item>

                        <Form.Item label="商品图片">
                            <PicturesWall ref={this.img} proPictures={proPictures}></PicturesWall>
                        </Form.Item>
                        <Form.Item label="商品描述">
                            <RichTextEditor ref={this.des} proDes={proDes}></RichTextEditor>
                        </Form.Item>
                        <Form.Item {...{ wrapperCol: { span: 8, offset: 8 } }}>
                            <Button type="primary" block onClick={this.submit}>提交</Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        );
    }
}
const WrappedRegistrationForm = Form.create()(AddProduct);
export default WrappedRegistrationForm;